<script setup>
//1.列表数据处理
import axios from "axios";
import { ref, computed, onMounted } from "vue";

//定义响应式数据list，渲染消费列表
const list = ref([]);

const getList = async () => {
  const res = await axios({ url: "https://applet-base-api-t.itheima.net/bill?creator=ivan666" });
  console.log(res.data.data);
  list.value = res.data.data;
};
onMounted(() => {
  getList();
});
// 2. 定义计算属性统计数据
const totalPrice = computed(() => {
  let total = 0;
  list.value.forEach((item) => (total += item.price));
  return total;
});

//2.新增数据处理
const name = ref('')
const price = ref('')

const addBill = async () => {
  // 表单验证
  if (!name.value.trim()) {
    alert('消费名称不能为空')
    return
  }
  
  const priceNum = parseFloat(price.value)
  if (isNaN(priceNum) || priceNum <= 0) {
    alert('请输入有效的消费金额')
    return
  }

  try {
    const res = await axios.post("https://applet-base-api-t.itheima.net/bill", {
      creator: "xzzz",
      name: name.value.trim(),
      price: priceNum
    })
    
    console.log('添加返回数据：', res.data)
    
    if (res.data.message === 'ok') {
      // 直接添加到列表，注意要添加到数组开头
      list.value.unshift({
        id: res.data.data.id,
        name: name.value.trim(),
        price: priceNum,
        creator: 'xzzz'
      })
      
      // 清空表单
      name.value = ''
      price.value = ''
      alert('添加成功！')
    } else {
      alert('添加失败，请重试')
    }
  } catch (error) {
    console.error("添加失败", error)
    alert('添加失败，请重试')
  }
}

//3.删除数据处理
const deleteBill = async (id) => {
  try {
    const res = await axios.delete(`https://applet-base-api-t.itheima.net/bill/${id}`)
    
    if (res.data.message === 'ok') {
      // 从列表中移除该项
      list.value = list.value.filter(item => item.id !== id)
      alert('删除成功！')
    } else {
      alert('删除失败，请重试')
    }
  } catch (error) {
    console.error("删除失败", error)
    alert('删除失败，请重试')
  }
}

 // 可以根据需要修改这个值
</script>

<template>
  <div id="app">
    <div class="contain">
      <!-- 左侧列表 -->
      <div class="list-box">
        <!-- 添加资产 -->
        <form class="my-form" @submit.prevent="addBill">
          <input 
            type="text" 
            class="form-control" 
            placeholder="消费名称" 
            v-model="name"
          />
          <input
            type="number"
            class="form-control"
            placeholder="消费价格"
            v-model="price"
          />
          <button type="submit" class="btn btn-primary">添加账单</button>
        </form>

        <table class="table table-hover">
          <thead>
            <tr>
              <th>编号</th>
              <th>消费名称</th>
              <th>消费价格</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in list" :key="item.id">
              <td>{{ index + 1 }}</td>
              <td>{{ item.name }}</td>
              <td :class="{ red: item.price >500 }">{{ item.price.toFixed(2) }}</td>
              <td>
                <a href="javascript:;" @click="deleteBill(item.id)">删除</a>
              </td>
            </tr>
            <!-- <tr>
              <td>2</td>
              <td>大衣</td>
              <td class="red">199.00</td>
              <td><a href="javascript:;">删除</a></td>
            </tr> -->
          </tbody>
          <tfoot>
            <tr>
              <td colspan="4">消费总计： {{ totalPrice.toFixed(2) }}</td>
            </tr>
          </tfoot>
        </table>
      </div>

      <!-- 右侧图表 -->
      <!-- <div class="echarts-box" id="main"></div> -->
    </div>
  </div>
</template>

<style scoped>
@import url(https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css);

.red {
  color: red !important;
}

.search {
  width: 300px;
  margin: 20px 0;
}

.my-form {
  display: flex;
  margin: 20px 0;
}

.my-form input {
  flex: 1;
  margin-right: 20px;
}

.table > :not(:first-child) {
  border-top: none;
}

.contain {
  display: flex;
  padding: 10px;
}

.list-box {
  flex: 1;
  padding: 0 30px;
}

.list-box a {
  text-decoration: none;
}

.echarts-box {
  width: 600px;
  height: 400px;
  padding: 30px;
  margin: 0 auto;
  border: 1px solid #ccc;
}

tfoot {
  font-weight: bold;
}

@media screen and (max-width: 1000px) {
  .contain {
    flex-wrap: wrap;
  }

  .list-box {
    width: 100%;
  }

  .echarts-box {
    margin-top: 30px;
  }
}
</style>
